import React, { useMemo } from 'react';
import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import './Breadcrumbs.scss';

const routeNameMap: Record<string, string> = {
  '': '首页',
  posts: '帖子中心',
  discussion: '讨论',
  share: '分享',
  trade: '交易',
  help: '求助',
  activities: '活动中心',
  knowledge: '知识库',
  products: '好价推荐',
  chat: '聊天室',
};

const buildBreadcrumbItems = (pathname: string) => {
  const segments = pathname.split('/').filter(Boolean);
  const items: { title: React.ReactNode }[] = [];

  // 首页
  items.push({ title: <Link to="/">首页</Link> });

  let pathAcc = '';
  for (let i = 0; i < segments.length; i++) {
    pathAcc += `/${segments[i]}`;
    const key = segments[i];
    const name = routeNameMap[key] || decodeURIComponent(key);
    const isLast = i === segments.length - 1;
    items.push({
      title: isLast ? (
        <span>{name}</span>
      ) : (
        <Link to={pathAcc}>{name}</Link>
      ),
    });
  }

  return items;
};

const Breadcrumbs: React.FC = () => {
  const location = useLocation();

  const items = useMemo(() => buildBreadcrumbItems(location.pathname), [location.pathname]);

  return (
    <div className="app-breadcrumbs">
      <Breadcrumb items={items} />
    </div>
  );
};

export default Breadcrumbs;
